package com.mobile.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.sys.service.SysUserManager;
import com.hsnn.medstgmini.util.Pagination;
import com.yspa.yspa.service.YspaInterfaceManager;

@Controller
public class MobilePwdChangeController{
	
	private static final Logger log = Logger.getLogger(MobilePwdChangeController.class);
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private HttpSession session;

	@Autowired
	private SysUserManager userManager;
	
	@Autowired
	private YspaInterfaceManager manager;
	
	@RequestMapping("/mobile/toPwdChange")
	public String toExpertPasswordChange(){
		Map<String,Object> userMap = (Map<String, Object>) session.getAttribute(Constants.USERINFO);
		if (userMap == null) {
			return "redirect:/mobile/login.html";
		}
		return "/mobile/pwdChange";
	}
	
	@RequestMapping("/mobile/pwdChange")
	@ResponseBody
	public Pagination passwordChange(Model model){
		Pagination page = new Pagination();
		String oldPassword = request.getParameter("oldPassword");//旧密码
		String newPassword = request.getParameter("newPassword");//新密码
		try{
			Map<String,Object> userMap = (Map<String, Object>) session.getAttribute(Constants.USERINFO);
			if (userMap == null) {
	            page.setMsg("请重新登录！");
	            page.setCode(-99);
				page.setSuccess(false);
				return page;
			}
			String password = (String)userMap.get("passwd");
			if(!oldPassword.equals(password)){
				page.setSuccess(false);
				page.setMsg("旧密码输入错误！请重新输入！");
			}
			
			String userno = userMap.get("userno").toString();
			manager.updatePasswd(userno, newPassword);
			userMap.put("passwd", newPassword);
			
			page.setMsg("密码修改成功");
			page.setSuccess(true);
		}catch(Exception e){
			log.error("",e);
            page.setSuccess(false);
            page.setMsg("密码修改失败");
		}
		return page;
	}
	@RequestMapping("/mobile/toExpertLogout")
	public String toExpertLogout(){
		HttpSession session = request.getSession();
		if (session != null) {
			session.setAttribute(Constants.USERINFO, null);
			session.invalidate();
		}
		return "/mobile/login";
	}
}
